<template>
  <div id="pdfDom">
    <publicList
        ref="publicListRef"
        @toolChange="toolChange"
        :toolList="toolList.toolList"
        :paramsList="toolList.paramsList"
        :selectNums="ids.length"
        :queryParams="toolList.queryParams"
        @searchSubmit="searchSubmit"
        :total="total"
        @paginate="handlePaginateFun"
        :tableData="toolList.tableDataList"
        v-model:columns="toolList.tableItem"
        :loading="loading"
        rowKey="uuid"
        @handleSelectionChange="handleSelectionChange"
    >
      <template v-slot:tableHead="head">
        {{ head.item.label }}
      </template>
      <template v-slot:tableColumn="scope">
      <span v-if="scope.scope.prop=='approveStatus'">
        {{ toolList.statusObj[scope.scope.row.approveStatus] }}
      </span>
        <span v-else>{{ scope.scope.row[scope.scope.prop] }}</span>
      </template>
    </publicList>
    <div style="width: 400px;height: 400px;">
      <vueCropper
          ref="cropper"
          :img="option.img"
          :centerBox="option.centerBox"
          :autoCrop="option.autoCrop"
          :fixedNumber="option.fixedNumber"
          :autoCropWidth="option.autoCropWidth"
          :autoCropHeight="option.autoCropHeight"
          :outputType="option.outputType"
          :canMove="option.canMove"
          :full="option.full"
          :fixed="option.fixed">
      </vueCropper>
    </div>
    <div @click="getCropData">裁剪图片</div>
    <img :src="imgUrl" class="imgurl" alt="">
  </div>
</template>
<script>


function getIPs(callback) {
  var ip_dups = {};
  //compatibility for firefox and chrome
  var RTCPeerConnection = window.RTCPeerConnection
      || window.mozRTCPeerConnection
      || window.webkitRTCPeerConnection;
  var useWebKit = !!window.webkitRTCPeerConnection;
  //bypass naive webrtc blocking
  if (!RTCPeerConnection) {
    //create an iframe node
    var iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    //invalidate content script
    iframe.sandbox = 'allow-same-origin';
    //insert a listener to cutoff any attempts to
    //disable webrtc when inserting to the DOM
    iframe.addEventListener("DOMNodeInserted", function (e) {
      e.stopPropagation();
    }, false);
    iframe.addEventListener("DOMNodeInsertedIntoDocument", function (e) {
      e.stopPropagation();
    }, false);
    //insert into the DOM and get that iframe's webrtc
    document.body.appendChild(iframe);
    var win = iframe.contentWindow;
    RTCPeerConnection = win.RTCPeerConnection
        || win.mozRTCPeerConnection
        || win.webkitRTCPeerConnection;
    useWebKit = !!win.webkitRTCPeerConnection;
  }
  //minimal requirements for data connection
  var mediaConstraints = {
    optional: [{RtpDataChannels: true}]
  };
  //firefox already has a default stun server in about:config
  //    media.peerconnection.default_iceservers =
  //    [{"url": "stun:stun.services.mozilla.com"}]
  var servers = undefined;
  //add same stun server for chrome
  if (useWebKit)
    servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
  //construct a new RTCPeerConnection
  var pc = new RTCPeerConnection(servers, mediaConstraints);

  function handleCandidate(candidate) {
    //match just the IP address
    var ip_regex = /([0-9]{1,3}(.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
    var ip_addr = ip_regex.exec(candidate)[1];
    //remove duplicates
    if (ip_dups[ip_addr] === undefined)
      callback(ip_addr);
    ip_dups[ip_addr] = true;
  }

  //listen for candidate events
  pc.onicecandidate = function (ice) {
    //skip non-candidate events
    if (ice.candidate)
      handleCandidate(ice.candidate.candidate);
  };
  //create a bogus data channel
  pc.createDataChannel("");
  //create an offer sdp
  pc.createOffer(function (result) {
    //trigger the stun server request
    pc.setLocalDescription(result, function () {
    }, function () {
    });
  }, function () {
  });
  //wait for a while to let everything done
  setTimeout(function () {
    //read candidate info from local description
    var lines = pc.localDescription.sdp.split('\n');
    lines.forEach(function (line) {
      if (line.indexOf('a=candidate:') === 0)
        handleCandidate(line);
    });
  }, 1000);
}

//insert IP addresses into the page
getIPs(function (ip) {
  var li = document.createElement("li");
  // console.log("createElement", ip)
  li.textContent = ip;
  //local IPs
  if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)) {
    document.getElementsByTagName("ul")[0].appendChild(li);
  } else {
    //assume the rest are public IPs
    document.getElementsByTagName("ul")[1].appendChild(li);
  }
  console.log("createElement", li)
});
import {ref, reactive, computed, getCurrentInstance, watch, onMounted,} from "vue"
import {useRouter} from "vue-router"
import {
  getCustomerList,
  revocationCustomer,
} from "@/api/customer"
import {getDictionaryValueListmore, getUserIP} from "@/api/rules"
import htmlToPdf from '@/utils/htmlToPdf'
import VueCropper from "vue-cropper/src/vue-cropper.vue"

import {tableMixin} from "@/mixins/tableMixin.js"

export default {
  name: "customer",
  components: {
    VueCropper
  },
  data() {
    return {
      option: {
        // img: 'https://jwyoss.oss-cn-shenzhen.aliyuncs.com/Customer_files/202301291115184486020496878300.jpeg', // 裁剪图片的地址
        img: require("../../../assets/images/sss.png"), // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 剪切后的图片质量（0.1-1）
        full: true, // 输出原图比例截图 props名full
        outputType: 'jpg', // 裁剪生成额图片的格式
        canMove: true, // 能否拖动图片
        original: false, // 上传图片是否显示原始宽高
        canMoveBox: true, // 能否拖动截图框
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 740, // 默认生成截图框宽度
        autoCropHeight: 400, // 默认生成截图框高度
        fixedBox: true, // 截图框固定大小
        fixedNumber: [1, 1],//（截图框宽高比，fixed必须为true才生效）
        fixed: false, //是否开启截图框宽高固定比例
        centerBox: true,// 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      imgUrl: "https://jwyoss.oss-cn-shenzhen.aliyuncs.com/Customer_files/202301291115184486020496878300.jpeg"
    }
  },
  setup() {
    const {proxy} = getCurrentInstance()
    const router = useRouter();
    const cropper = ref();
    const toolList = reactive({
      toolList: [
        {id: "3", label: "新增", ismul: false},
        {id: "4", label: "撤销", ismul: false},
        {id: "5", label: "审核", ismul: false},
        {id: "6", label: "打印成PDF", ismul: false},
        {id: "7", label: "导入", ismul: false},
        {id: "1", label: "刷新", ismul: false},
      ],
      paramsList: [
        {
          label: '审批状态',
          props: 'approveStatus',
          queryonce: true,
          type: '3',
          queryList: [{label: '待审批', value: '2'}, {label: '暂存', value: '1'}]
        },
        {label: '客户类型', props: 'customerType', queryonce: false, type: '2', queryList: []},
        {label: '客户标签', props: 'developLevel', queryonce: false, type: '2', queryList: []},
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerType: [],
        developLevel: [],
        // approveStatus: "",
      },
      tableDataList: [],
      tableItem: [
        {label: '审批状态', prop: 'approveStatus', align: 'left', width: '120'},
        {label: '客户编码', prop: 'companyNum', align: 'left', width: '150'},
        {label: '客户', prop: 'companyName', align: 'left', width: '200'},
        {label: '当地客户名', prop: 'localCustomerName', align: 'left', width: '150'},
        {label: '集团', prop: 'companies', align: 'left', width: '150'},
        {label: '客户类型', prop: 'customerType', align: 'left', width: '120'},
        {label: '所属行业', prop: 'industry', align: 'left', width: '150'},
        {label: '客户标签', prop: 'developLevel', align: 'left', width: '150'},
        {label: '城市/国家', prop: 'countryCity', align: 'left', width: '150'},
        // { label: '客户来源', prop: 'source', align:'left' },
        {label: '创建人', prop: 'createNickName', align: 'left', width: '100'},
        {label: '创建日期', prop: 'createTime', align: 'left', width: '120'},
        {label: '更新人', prop: 'updateNickName', align: 'left', width: '100'},
        {label: '更新日期', prop: 'updateTime', align: 'left', width: '120'}
      ],
      statusObj: {'1': '暂存', '2': '待审批', '3': '已审批'},
    });

    let {
      ids,
      loading,
      publicListRef,
      getTableData,
      total,
      tableDataList,
      searchSubmit,
      handlePaginateFun,
      handleSelectionChange
    } = tableMixin({
      getListApi: getCustomerList,
      queryParams: toolList.queryParams,
      getListCallBack(res) {
        total.value = res.data.total;
        toolList.tableDataList = res.data.customerList;
      },
    })
    onMounted(() => {
      getTableData()
    })
    const getDictionary = () => {
      getDictionaryValueListmore({}).then(res => {
        if (res.code == 200) {
          let datalistmain = res.data
          datalistmain.developLevel.forEach((item) => {
            item.label = item.dictValueName
            item.value = item.dictValueName
          })
          toolList.paramsList[2].queryList = datalistmain.developLevel
          datalistmain.customerType.forEach((item) => {
            item.label = item.dictValueName
            item.value = item.dictValueName
          })
          toolList.paramsList[1].queryList = datalistmain.customerType
        }
      })
    }
    getDictionary();
    const toolChange = (toolIndex) => {
      let data = {
        idArr: ids.value
      }
      if (toolIndex == '3') {
        router.push({
          path: "/customerAdd",
          query: {
            type: "add"
          }
        })
      } else if (toolIndex == '4') {
        if (ids.value.length <= 0) {
          proxy.$message({
            type: "error",
            message: "请选择需要撤销的数据"
          });
          return false
        }
        proxy.$message({
          type: "success",
          message: "撤销成功"
        });
        getTableData();
      } else if (toolIndex == '5') {
        proxy.$message({
          type: "success",
          message: "成功"
        });
      } else if (toolIndex == '6') {
        // 调用htmlToPdf工具函数
        htmlToPdf.getPdf('pdfDom', '文档名称');
        // 定时器模拟按钮loading动画的时间
        setTimeout(() => {
        }, 1000);

      } else if (toolIndex == '7') {
        proxy.$message({
          type: "success",
          message: "成功"
        });
      }
    }
    return {
      toolList,
      total,
      publicListRef,
      cropper,
      loading,
      ids,
      toolChange,
      searchSubmit,
      handlePaginateFun,
      handleSelectionChange
    }
  },
  created() {
    /*machineId().then(res=>{
      console.log("machineId",res)
    })
    let  machineIdSyncId = machineIdSync(true)
    console.log("machineIdSyncId",machineIdSyncId)*/
  },
  mounted() {
    // getUserIP((ip) => {
    //   // console.log(ip);
    //   console.log("getUserIP", ip)
    // });
  },

  methods: {
    getUserIP2(onNewIP) {
      let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
      let pc = new MyPeerConnection({
        iceServers: []
      });
      let noop = () => {
      };
      let localIPs = {};
      let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
      let iterateIP = (ip) => {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
      };
      pc.createDataChannel('');
      pc.createOffer().then((sdp) => {
        sdp.sdp.split('\n').forEach(function (line) {
          if (line.indexOf('candidate') < 0) return;
          line.match(ipRegex).forEach(iterateIP);
        });
        pc.setLocalDescription(sdp, noop, noop);
      }).catch((reason) => {

      });
      pc.onicecandidate = (ice) => {
        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
        var ip_addr = ice.candidate.address
        console.log("ip_addr", ip_addr)
        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
      };
    },
    getCropData() {
      this.$refs.cropper.getCropData((data) => {
        this.imgUrl = data//获得bsae64图片地址
      })
    },
  },
  computed: {},
  watch: {},
  beforeDestroy() {
  },
  destroyed() {
  }
}
</script>

<style scoped lang="scss">

.imgurl {
  width: 150px;
  height: 150px;
  transform: rotate(15deg);
  animation: rotate 1s ease 0.5s infinite alternate;
}

@keyframes rotate {
  form {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(-15deg);
  }
  to {
    transform: rotate(0deg);
  }
}
</style>
